package com.yuven.appframework.util

import android.content.Context
import android.content.SharedPreferences
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.Build
import android.telephony.TelephonyManager
import android.text.TextUtils
import com.yuven.appframework.manager.PackageInfoServer
import com.yuven.baselib.utils.Logger
import com.yuven.baselib.utils.NetHelper
import com.yuven.baselib.utils.NetHelper.NET_LINE
import com.yuven.baselib.utils.NetHelper.NET_WIFI
import java.util.Locale
import java.util.UUID

object DeviceIdUtil {

    val TAG = "DeviceIdUtil"
    val DEVICE_ID_SP_KEY = "mbox_device_id_key"
    var mSpref: SharedPreferences? = null
    var deviceId = ""

    //创建设备id
    fun init(context: Context) {
        val appName = PackageInfoServer.getAppName(context)
        mSpref = context.getSharedPreferences(appName, Context.MODE_PRIVATE)
        deviceId = mSpref?.getString(DEVICE_ID_SP_KEY, "").toString()
        if (TextUtils.isEmpty(deviceId)) {
            deviceId = UUID.randomUUID().toString()
            Logger.i(TAG, "create deviceId : $deviceId")
            var editor = mSpref?.edit()
            editor?.putString(DEVICE_ID_SP_KEY, deviceId)
            editor?.commit()
        }
        Logger.i(TAG, "init deviceId : $deviceId")
    }

    fun getAndroidVersion(): String {
        return "Android " + Build.VERSION.RELEASE
    }

    /**
     * 检查网络是否可用
     *
     * @param paramContext
     * @return
     */
    fun checkEnable(paramContext: Context): Boolean {
        val i = false
        val localNetworkInfo =
            (paramContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
        return if (localNetworkInfo != null && localNetworkInfo.isAvailable) true else false
    }

    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    fun int2ip(ipInt: Int): String? {
        val sb = StringBuilder()
        sb.append(ipInt and 0xFF).append(".")
        sb.append(ipInt shr 8 and 0xFF).append(".")
        sb.append(ipInt shr 16 and 0xFF).append(".")
        sb.append(ipInt shr 24 and 0xFF)
        return sb.toString()
    }

    /**
     * 获取当前ip地址
     *
     * @param context
     * @return
     */
    fun getLocalIpAddress(context: Context): String? {
        return try {
            val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
            val wifiInfo = wifiManager.connectionInfo
            val i = wifiInfo.ipAddress
            int2ip(i)
        } catch (ex: Exception) {
            null
        }
    }


    /**
     * 返回当前程序版本名
     */
    fun getAppVersionName(context: Context): String? {
        return try {
            var pm = context.getPackageManager();
            var pi = pm.getPackageInfo(context.getPackageName(), 0);
            "V" + pi.versionName;
        } catch (e: java.lang.Exception) {
            Logger.e(TAG, "获取版本名失败 ${e.message}")
            null
        }
    }

    private fun getDisplay(context: Context): String {
        val display = getDisplayByContext(context)
        return if (display != null) {
            display[0].toString() + "x" + display[1]
        } else ""
    }

    /**
     * 获取屏幕分辨率
     *
     * @param context
     * @return
     */
    fun getDisplayByContext(context: Context): IntArray? {
        val displayMetrics = context.resources.displayMetrics
        val screenWidth = displayMetrics.widthPixels
        val screenHeight = displayMetrics.heightPixels
        val result = IntArray(2)
        result[0] = screenWidth
        result[1] = screenHeight
        return result
    }

    fun getNetWorkDesc(): String {
        val type = NetHelper.getNetworkType()
        if (type == NET_LINE) {
            return "wired"
        }
        if (type == NET_WIFI) {
            return "wifi"
        }
        return "${type}g"
    }


    /**
     * 判断是否包含SIM卡
     *
     * @return 状态
     */
    fun hasSimCard(context: Context): Boolean {
        val telMgr = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val simState = telMgr.simState
        var result = true
        when (simState) {
            TelephonyManager.SIM_STATE_ABSENT -> result = false // 没有SIM卡
            TelephonyManager.SIM_STATE_UNKNOWN -> result = false
        }
        return result
    }

    fun getHideNumStr(mobile: String): String? {
        if (mobile == null || mobile.length < 11) {
            return mobile
        }
        var StrBuilder = StringBuilder()
        StrBuilder.append(mobile.substring(0, 3))
        StrBuilder.append("****")
        StrBuilder.append(mobile.substring(7, 11))
        return StrBuilder.toString()
    }


    fun getIMEI1(paramContext: Context): String? {
        return try {
            val telephonyManager =
                paramContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            val str = telephonyManager.javaClass.getMethod(
                "getImei",
                *arrayOf<Class<*>?>(Int::class.javaPrimitiveType)
            ).invoke(telephonyManager, *arrayOf<Any>(Integer.valueOf(0))) as String?
            val bool = TextUtils.isEmpty(str)
            if (!bool) str else ""
        } catch (exception: java.lang.Exception) {
            val stringBuilder = java.lang.StringBuilder()
            stringBuilder.append("")
            stringBuilder.append(exception.message)
            Logger.i("getIMEI1:exception:${stringBuilder.toString()}")
            ""
        }
    }

    fun getIMEI2(paramContext: Context): String? {
        return try {
            val telephonyManager =
                paramContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            val str = telephonyManager.javaClass.getMethod(
                "getImei", *arrayOf<Class<*>?>(
                    Int::class.javaPrimitiveType
                )
            ).invoke(telephonyManager, *arrayOf<Any>(Integer.valueOf(1))) as String
            val bool = TextUtils.isEmpty(str)
            if (!bool) str else ""
        } catch (exception: java.lang.Exception) {
            val stringBuilder = java.lang.StringBuilder()
            stringBuilder.append("")
            stringBuilder.append(exception.message)
            Logger.i("getIMEI2:exception:${stringBuilder.toString()}")
            ""
        }
    }

    fun getSerialNumber(): String? {
        var serial: String? = ""
        try {
            serial = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 8.0
                Build.getSerial()
            } else {
                Build.SERIAL
            }
            if (TextUtils.isEmpty(serial) || "unknown".equals(serial, ignoreCase = true)) {
                val c = Class.forName("android.os.SystemProperties")
                val get = c.getMethod("get", String::class.java)
                serial = get.invoke(c, "ro.serialno") as String
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            Logger.i("获取设备序列号失败" + e.message)
        }
        return serial
    }

    fun getSystemLanguage(): String {
        val locale = Locale.getDefault() ?: return "en"
        // Special case Chinese
        return if (Locale.SIMPLIFIED_CHINESE == locale) {
            "zh-rCN"
        } else locale.language
    }
}